package com.yh.csx.etl.config;

import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;

/**
 * 数据源管理器
 * 
 * @author Robin.Wang
 * @date 2020-03-20
 *
 */

@Configuration
@ConfigurationProperties(prefix = "etl.config")
public class EtlDataSourceManager {
    private static final Logger log = LoggerFactory.getLogger(EtlDataSourceManager.class);

    public final static Map<String, DruidDataSource> DATA_SOURCES = new ConcurrentHashMap<>(); // key对应的数据源

    private Map<String, EtlDataSource> datasource;

    public Map<String, EtlDataSource> getDatasource() {
        return datasource;
    }

    public void setDatasource(Map<String, EtlDataSource> datasource) {
        this.datasource = datasource;

        if (datasource != null) {
            for (Map.Entry<String, EtlDataSource> entry : datasource.entrySet()) {
                EtlDataSource datasourceConfig = entry.getValue();
                // 加载数据源连接池
                DruidDataSource ds = new DruidDataSource();
                ds.setDriverClassName(datasourceConfig.getDriver());
                ds.setUrl(datasourceConfig.getUrl());
                ds.setUsername(datasourceConfig.getUsername());
                ds.setPassword(datasourceConfig.getPassword());
                ds.setInitialSize(1);
                ds.setMinIdle(1);
                ds.setMaxActive(datasourceConfig.getMaxActive());
                ds.setMaxWait(datasourceConfig.getMaxWait());
                ds.setTestWhileIdle(true);
                ds.setValidationQuery("select 1;");
                ds.setValidationQueryTimeout(5000);
                ds.setTimeBetweenEvictionRunsMillis(60000);
                ds.setMinEvictableIdleTimeMillis(300000);
                try {
                    ds.init();
                } catch (SQLException e) {
                    log.error("error connect to db server: {} ", e);
                    ds.close();
                    throw new RuntimeException(e);

                }
                DATA_SOURCES.put(entry.getKey(), ds);
                log.info("success connect to datasource {}", entry.getKey());
            }
        }
    }

}
